package com.flute.framework;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import com.flute.framework.util.ftp.IFileOperation;

public class LuceneRecords {
	public static final String RECORD_COUNT = "record.count";
	private String folder;
	private IFileOperation oper;

	public LuceneRecords(String folder, IFileOperation oper) {
		this.folder = folder;
		this.oper = oper;
	}

	public boolean exists() {
		/*
		 * File file = new File(folder, RECORD_COUNT); return file.exists() &&
		 * file.length() > 0;
		 */
		try {
			String uri = oper.combin(folder, RECORD_COUNT);
			return oper.exists(uri) || oper.size(uri) > 0;
		} catch (Exception e) {
			return false;
		}
	}

	public void setCount(int count) throws IOException {
		/*
		 * File file = new File(folder, RECORD_COUNT); if (!file.exists()) {
		 * file.createNewFile(); } FileWriter fw = new FileWriter(file, false);
		 * fw.write(String.valueOf(count)); fw.close();
		 */
		String uri = oper.combin(folder, RECORD_COUNT);
		ByteArrayInputStream is = null;
		try {
			if (!oper.exists(uri)) {
				oper.createNewFile(uri);
				byte[] bs = String.valueOf(count).getBytes();
				is = new ByteArrayInputStream(bs);
				oper.save(uri, is);
			}
		} catch (Exception e) {
			throw new IOException(e.getMessage());
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
				}
			}
		}
	}

	public int getCount() throws IOException {
		/*
		 * File file = new File(folder, RECORD_COUNT); if (!file.exists()) {
		 * return 0; } else { BufferedReader fr = new BufferedReader(new
		 * FileReader(file)); String count = fr.readLine(); fr.close(); try {
		 * return Integer.valueOf(count); } catch (Exception e) { return 0; } }
		 */
		String uri = oper.combin(folder, RECORD_COUNT);
		BufferedReader reader = null;
		InputStreamReader in = null;
		try {
			if (oper.isFile(uri)) {
				in = new InputStreamReader(oper.load(uri));
				reader = new BufferedReader(in);
				String countStr = reader.readLine();
				try {
					return Integer.parseInt(countStr);
				} catch (NumberFormatException e) {
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
				}
			}
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
				}
			}
		}
		return 0;
	}

	public boolean delete() {
		/*
		 * File file = new File(folder, RECORD_COUNT); if (file.exists()) {
		 * return file.delete(); }
		 * 
		 * return true;
		 */
		String uri = oper.combin(folder, RECORD_COUNT);
		try {
			if (oper.exists(uri)) {
				return oper.delete(uri);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;

	}
}
